#!/usr/bin/env sh

PATH=$PATH:$(dirname "$0")

# add a hash to check for simple tampering on a file
# the hash signs the content of the file, a random number (added with the
# hash), and the file name (except when the option -noname is given)
sign_file() {
  name="name"
  if [ "$1" = "-noname" ]
  then
    name=""
    shift
  fi
  if [ "$#" -ne 1 ] && [ "$#" -ne 2 ]
  then
    echo "Error: sign_file requires 1 or 2 arguments." >&2
    echo "$@"
    return 1
  fi
  source=$1
  if ! [ -f "$source" ] || ! [ -r "$source" ]
  then
    echo "Error: sign_file file $source doesn't exist, or is not readable." >&2
    return 1
  fi

  if [ "$#" -eq 2 ]
  then
    target=$2
    [ -d "$target" ] && target=$target/$(basename "$source")
    tempfile=$target
  else
    target=$source
    tempfile=$(mktemp)
  fi
  rd=$(RANDOM)
  if [ -s "$source" ]
  then
    sum=$(echo "${name:+$(basename "$target")}@$rd" | cat - "$source" | checksum)
    echo "$sum@$rd" | cat - "$source" > "$tempfile"
  else
    sum=$(echo "${name:+$(basename "$target")}@$rd" | checksum)
    echo "$sum@$rd" > "$tempfile"
  fi
  if [ "$tempfile" != "$target" ]
  then
    cat "$tempfile" > "$target"
    rm -f "$tempfile"
  fi
}

sign_file "$@"
